package com.txr.news.controller;

import com.txr.news.pojo.Code;
import com.txr.news.pojo.Result;
import com.txr.news.pojo.entity.User;
import com.txr.news.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@CrossOrigin
@AllArgsConstructor
@RequestMapping("/my")
public class UserController {
    UserService userService;

    @GetMapping("/userinfo")
    public Result getUserInfo(HttpServletRequest request){
        Result result = new Result(0,"get userinfo success");

        Integer userId = (Integer) request.getAttribute("userId");
        User user = userService.getUserInfo(userId);

        user.setPassword("");
        result.setData(user);

        return result;
    }

    @PostMapping("/userinfo")
    public Result updateUserInfo(User user){
        Result result = new Result(0,"更新用户信息成功！");

        Boolean flag = userService.updateUserInfo(user);
        if (!flag){
            result.setStatus(1);
            result.setMsg("更新用户信息失败");
        }
        return result;
    }

    @PostMapping("/updatepwd")
    public Result updatePwd(HttpServletRequest request,String oldPwd,String newPwd){
        //Result result = new Result(0,"更新密码成功！");
        Integer userId = (Integer) request.getAttribute("userId");
        Result result = userService.updateUserPwd(userId, oldPwd, newPwd);
        return result;
    }

    @PostMapping("/update/avatar")
    public Result updateUserPic(HttpServletRequest request, String avatar){
        Result result = new Result(0,"更新头像成功！");
        Integer userId = (Integer) request.getAttribute("userId");
        Boolean flag = userService.updateUserPic(userId, avatar);
        if (!flag){
            result.setStatus(1);
            result.setMsg("用户不存在，更新头像失败！");
        }
        return result;
    }
}
